/**
 * Created by Administrator on 2017/3/29 0029.
 */
import React from "react";
import { Modal,message } from 'antd';
import Relay from "react-relay";
import InputBox from "../../../common/InputBox"
import Confirm from "../../../common/Confirm"
import GetQiNiuTokenMutation from "./mutation/GetQiNiuTokenMutation"
import SaveImageMutation from "./mutation/SaveImageMutation"
import "../css/UpLoadModal.css"

import Config from "../../../util/Config"

export default class DetailUploadModal extends React.Component{
    constructor(props){
        super(props)
        this.state={
            visible:false,
            focus:'选择文件',
            hint:'只可以',
            opacity:0,
            text:'',
            filename:[],
            isupdata:false
        }
        this.myfile = '';
        this.filename=[];
    }

    closemodal(){
        !this.state.isupdata && this.setState({visible:false});
    }

    textChange(e){

    }

    onfocus(){
        this.setState({
            focus:''
        });
    }

    pickfile(){

    }

    afterClose(){
        this.refs.upfile.value = ''
        this.myfile = ''
        this.setState({
            opacity:0,
            focus:'选择文件',
            text:''
        });
    }

    uploadfile(){
        let name = this.state.text;
        let filename = this.file;
        let size = filename.size
        let i = Math.floor(Math.log(size) / Math.log(1000));
        let filesizem = (size / Math.pow(1000, 2)).toPrecision(3)
        let str_temp = (filename.name).replace(/[\u4e00-\u9fa5]/g, 'aa')//将汉字替换为aa
        if (str_temp.length > 100) {
            message.info('文件名不能超过100字符')
            return
        }
        if(filesizem>10){
            this.setState({
                opacity:1,
                hint:'上传文件不能大于10M',
            });
            return
        }
        if(this.file==''){
            this.setState({
                opacity:1,
                hint:'请选择文件',
            });
            return
        }

        if(name.indexOf('.')<0){
            this.setState({
                opacity:1,
                hint:'文件格式不正确',
            });
            return
        }
        let suffixsub = name.split('.');
        let suffix = suffixsub[suffixsub.length-1].toLowerCase();
        let limitlist = ['pdf','docx','doc','xlsx','xls','bmp','png','jpeg','gif','tiff','jpg'];

        if(this.contains(limitlist,suffix)){
            this.setState({
                opacity:0,
            });
            this.upload();
        }else{
            this.setState({
                opacity:1,
                hint:'只能上传pdf、docx、doc、xlsx、xls及基本图片类型',
            });
        }
    }

    contains(arr, obj) {
        let i = arr.length;
        while (i--) {
            if (arr[i] === obj) {
                return true;
            }
        }
        return false;
    }


    chosefile(){
        this.setState({
            opacity: 0,
        },()=>{
            if(document.getElementById('choiceFileupdata'+this.props.mid).files[0]){
                this.file = document.getElementById('choiceFileupdata'+this.props.mid).files[0];
                let name = this.file.name;
                this.setState({
                    text:name
                });
            }
        })
    }

    upload(){
        Relay.Store.commitUpdate(
            new GetQiNiuTokenMutation({}), {
                onSuccess: (res) => {
                    // console.warn(res);
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken
                        this.token = qiniutoken;
                        this.upLoadFile(this.file,qiniutoken)
                    }
                }
            }
        )
    }

    upLoadFile(file, token) {
        message.config({
            top: 30
        })

        this.setState({
            isupdata:true
        });
        const hide = message.loading('正在上传中，请稍等', 0);
        let upLoadUrl = "http://up-z2.qiniu.com";
        let xhr = new XMLHttpRequest();
        xhr.open("POST", upLoadUrl, true);
        let timestamp = Date.parse(new Date());
        let fileKey = timestamp+this.file.name;
        let formData = new FormData();
        formData.append('file', file);
        formData.append('token', token);
        formData.append('key',fileKey);
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    this.setState({
                        visible:false
                    });
                    let res = JSON.parse(xhr.responseText);
                    // this.props.addpact(this.myfile.name,res.hash);
                    setTimeout(hide);
                    Relay.Store.commitUpdate(
                        new SaveImageMutation({
                            realName:this.file.name,
                            token:res.hash,
                            url:Config.qiuniu+res.key
                        }),
                        {
                            onFailure: () => {
                                this.setState({
                                    isupdata:false
                                });

                            },
                            onSuccess: (response) => {
                                this.setState({
                                    isupdata:false
                                });
                                let errorCode = response.saveImage.saveImage.errorCode;
                                if(errorCode ==0){
                                    let realName = response.saveImage.saveImage.imageStorge.realName;
                                    let imageUrl = response.saveImage.saveImage.imageStorge.imageUrl;
                                    let sid  = response.saveImage.saveImage.imageStorge.sid;
                                    this.props.addpact(realName,res.hash,imageUrl,fileKey,sid);
                                }
                            }
                        }
                    )

                } else {
                    alert('上传失败')
                }
            }
        };
        xhr.send(formData);
    }

    render(){
        return (
            <Modal
                visible={this.state.visible}
                footer={null} title={'附件上传'}
                onCancel={this.closemodal.bind(this)}
                width={654} afterClose={this.afterClose.bind(this)}
                className="batchhint_modal order_updata_excel"
            >
                <p style={{fontSize:16,marginLeft:28}}>上传文件不可超过10M</p>
                <input className="order_updata_modal_border" placeholder={this.state.focus} style={{height:30,width:317,paddingLeft:10,marginTop:20,marginLeft:28}} onChange={this.textChange.bind(this)} onFocus={this.onfocus.bind(this)} value={this.state.text}/>
                <span className="order_updata_modal_border" style={{float:'right',height:30,width:38,marginRight:226,marginTop:20,borderLeftWidth:"0",cursor:'pointer'}} onClick={this.pickfile.bind(this)}>
                    <input ref={'upfile'} type="file" style={{opacity:0,position:"absolute",height:30,width:38}} id={"choiceFileupdata"+this.props.mid} onChange={this.chosefile.bind(this)}/>
                    <img src={require('./img/fileupload.png')} style={{marginLeft:10,marginTop:10}}/></span>
                <button className="order_updata_modal_buttonup" onClick={this.uploadfile.bind(this)} disabled = {this.state.isupdata}>上传</button>
                <button className="order_updata_modal_buttoncn" onClick={this.closemodal.bind(this)} disabled = {this.state.isupdata}>取消</button>
                <span className="order_updata_modal_hint" style={{opacity:this.state.opacity}}>{this.state.hint}</span>
            </Modal>
        )
    }
}
